//
//  XZMyExamVC.m
//  Teecloud
//
//  Created by PC on 2018/10/25.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMyExamVC.h"
#import "XZSearchBar.h"
#import "XZExamModel.h"
#import "XZMyExamCell.h"
#import "GMExamResultVC.h"
#import "GMExaminationVC.h"
@interface XZMyExamVC ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XZSearchBar *searchBar;

@property (nonatomic, copy) NSString *key;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end
#define EXAMCELL @"XZMyExamCell"
@implementation XZMyExamVC
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    [self creatTitleView];
    [self pullNewsData];
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.key = self.searchBar.text;
    [self pullNewsData];
}
//搜索框
- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = @"输入关键字";
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XZMyExamCell *cell = [tableView dequeueReusableCellWithIdentifier:EXAMCELL];
    XZExamModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80.f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];

    XZExamModel *model = self.dataSource[indexPath.row];
    //我的资源 - 试卷考试 - 考试须知
    if ([model.TestStatus integerValue] == 1 || [model.TestStatus integerValue] == 2) {
        GMExaminationVC *examinationVC = [[GMExaminationVC alloc]init];
        examinationVC.resId = model.Id;
        examinationVC.TestRoomId = model.TestRoomId;
        examinationVC.TestTimeId = model.TestTimeId;
        [self.navigationController pushViewController:examinationVC animated:true];
        return;
    }
    
    //我的资源 - 试卷考试 - 答题卡 - 结果
    if ([model.TestStatus integerValue] == 9 && [model.PassMode integerValue] >=0) {
        GMExamResultVC *examResultVC = [[GMExamResultVC alloc]init];
        examResultVC.examId = model.Id;
        [self.navigationController pushViewController:examResultVC animated:true];
    }
    
}

#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //注册
        [_tableView registerNib:[UINib nibWithNibName:@"XZMyExamCell" bundle:nil] forCellReuseIdentifier:EXAMCELL];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullNewsData)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreNewsData)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
#pragma mark - MJRefresh
- (void)pullNewsData{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyTestList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.dataSource removeAllObjects];
                NSArray *array = [XZExamModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:array];
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)addMoreNewsData{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyTestList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZExamModel mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakself.dataSource addObjectsFromArray:newsArray];
                if (dataInfo.count>0) {
                    [weakself.tableView.mj_footer endRefreshing];
                    [weakself.tableView.mj_header endRefreshing];
                    [weakself.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
@end
